import { useEffect } from "react";
import { Button, Form, Input } from "antd";
import { useNavigate } from "react-router-dom";
import Cookies from "js-cookie";

import useSecurity from "../hooks/useSecurity";

const SignIn = () => {
  const { login, loginWithToken } = useSecurity();
  const navigate = useNavigate();

  useEffect(() => {
    const userIDCookie = Cookies.get("userID");
    if (userIDCookie) {
      (async () => {
        const success = await loginWithToken(userIDCookie);
        if (success) {
          navigate("/", { replace: true });
        }
      })();
    }
  }, [loginWithToken, navigate]);

  const action = async (values) => {
    const { username, password } = values;
    const success = await login(username, password);
    if (success) {
      navigate("/", { replace: true });
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <Form
      name="basic"
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ maxWidth: 600 }}
      initialValues={{ remember: true }}
      onFinish={action}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="Username"
        name="username"
        rules={[{ required: true, message: "Please input your username!" }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="Password"
        name="password"
        rules={[{ required: true, message: "Please input your password!" }]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 8, span: 8 }}>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

export default SignIn;
